<?php
namespace app\controllers; //命名空间
use yii\web\Controller; // 导入Controller
use app\controllers\BaseController; //导入基础controller（内含各种基础使用函数）
use app\models\User; // 准考证模型
use yii\web\Session;
use Yii; // 导入Yii

//用户功能
/*
1、注册：龙哥
2、登陆：嘉丽
3、检查登陆态：嘉丽
 
5、修改昵称、密码：龙哥
*/

class UserController extends Controller{

    public $enableCsrfValidation = false;

    /*************罗韵龙**********/
	//token实现登陆态确认
	//注册用户 同时生成token
	public function actionRegisteruser(){
		if( Yii::$app->request->isPost ){
            //数据初始化
            $user = new User();
            //接收数据
			$postData = Yii::$app->request->post(); //获取session
			$uName = $postData['name']; //用户昵称
			$uEmail = $postData['mail']; //用户邮箱
			$uNumber = $postData['number']; //用户手机号码
			$uPassword = $postData['password']; //用户密码

             //用户数据
            $uInfo = array( //user的数组 方便用于检测错误
                'uName' => $uName,
                'uEmail' => $uEmail,
                'uNumber' => $uNumber,
                'uPassword' => $uPassword,
            );
            //检查用户信息的错误
            $errorContent = $this->checkAll($uInfo);
            if(!empty($errorContent)){   
                $data = array(
                    '0' => -3, 
                    '1' => $errorContent,
                );
                return BaseController::FailRespone($data);
                exit(0);
            }

            //验证是否有重新注册
            $checkkey = $uNumber.'_p:';
            $checkdata = Yii::$app->redis->get($checkkey);
            //从数据库里面查看
            $check_mail = $user->checkBymail($uEmail);
            $check_number = $user->checkBynumber($uNumber);
            //从缓存里面查看
            if(!empty($checkdata)){
                $content = "此用户已经注册了";
                $data = array(
                    '0' => -3,
                    '1' => $content,
                );
                return BaseController::FailRespone($data); 
                exit(0);
            }else if($check_number){
                $content = "已有用户使用此手机号码了";
                $data = array(
                    '0' => -3,
                    '1' => $content,
                );
                return BaseController::FailRespone($data); 
                exit(0);
            }else if($check_mail){
                $content = "已有用户使用此邮箱了";
                $data = array(
                    '0' => -3,
                    '1' => $content,
                );
                return BaseController::FailRespone($data); 
                exit(0);
            }
	
			//数据库插入数据
			$result = $user->insertUser($uInfo);
            $uInfo = $user->getAll($uInfo['uNumber']);
            //进行数据缓存 缓存密码
            $key_number = $uNumber.'_p:';
            $key_mail = $uEmail.'_p:';
            Yii::$app->redis->set($key_number, json_encode($uInfo));
            Yii::$app->redis->set($key_mail, json_encode($uInfo));
			if($result){
				$data = '成功创建用户';
				return BaseController::SuccessRespone($data);
			}
		}else{
            $content = "接收的posts数据为空";
            $data = array(
                '0' => -2,
                '1' => $content,
            );
            return BaseController::FailRespone($data);   
        }
        exit(0);
	}

    /*************张嘉丽**********/
	//登陆用户
	public function actionLogin(){
        if( Yii::$app->request->isPost ){
            //数据初始化
            $user = new User();
            $redis = Yii::$app->redis;

            //接收页面发来的账号和密码
            $postData = Yii::$app->request->post(); //获取session
            $account = $postData['account']; //account为接收字段
            $password = $postData['password'];//密码
            //页面发来的数据是否为空或者不存在
            if(empty($account) || empty($password)){
                $content = "账号或者密码为空";
                $data = array(
                    '0' => -2,
                    '1' => $content,
                );
                return BaseController::FailRespone($data);
                exit(0);
            }

            //用户在注册后会用缓存储存用户id（数据库uId）
            //验证是否存在这个账号account
            $key = $account.'_p:';
            $uInfo = Yii::$app->redis->get($key);
            $uInfo = json_decode($uInfo, true);
            //数据库信息抽取密码
            if(empty($uInfo)){
                $type = $this->judgeAccount($account);
                //用户在注册时会用uMail和uNumber注册，随便填任何一个进行登录
                //判断account是哪一个类型账号 mail还是number
                //抽取存取的密码password
                if($type == 'mail'){
                    $uInfo = $user->getByMail($account);
                }else if($type == 'number'){
                    $uInfo = $user->getByNumber($account);
                }
                if(empty($uInfo)){
                    $content = "账号错误，并没有找到账号";
                    $data = array(
                        '0' => 0,
                        '1' => $content,
                    );
                    return BaseController::FailRespone($data);
                    exit(0);
                }
            }
            //验证用户密码是否正确 比较密码
            $uPassword = $uInfo['uPassword'];
            if($password != $uPassword){
                $content = "密码错误，请重新输入";
                $data = array(
                    '0' => -3,
                    '1' => $content,
                );
                return BaseController::FailRespone($data);
                exit(0);
            }
            //创建一个redis信息储存来储存用户id
            $redis_values = $uInfo['uId'];

            //创建sesseion
            $session = BaseController::_3rd_session(32); //用户标示
            $key = '_3rd_session:' . $session;
            $redis->setex($key, 1209600, json_encode($redis_values));
            //组合信息
            $user_info = array(
                'uName' => $uInfo['uName'],
                'uHeadurl' => $uInfo['uHeadurl'],
                'session' => $session,
            );
            //返回session给前端
            return BaseController::SuccessRespone($user_info);
        }else{
            $content = "接收的posts数据为空";
            $data = array(
                '0' => -2,
                '1' => $content,
            );
            return BaseController::FailRespone($data);   
        }
        exit(0);
	}
    /*************张嘉丽**********/
    //检查登陆态
    public function actionChecklogin(){
        if( Yii::$app->request->isPost ){
            //接收前端请求过来的session
            $postData = Yii::$app->request->post(); //获取session
            if(empty($postData['session'])){
                $data = array(
                    'session' => NUll,
                    'loginstate' => false,
                );
                $data = array(
                    '0' => 0,
                    '1' => $data,
                );
                return BaseController::FailRespone($data);
                exit(0);
            }
            $session = $postData['session'];
            //判断一下session是否存在
            $key = '_3rd_session:' . $session;
            $redis_value = Yii::$app->redis->get($key);
            //不存在的话就告诉前端，这个用户已退出登录
            if(empty($redis_value)){
                $data = array(
                    'session' => NUll,
                    'loginstate' => false,
                );
                $data = array(
                    '0' => 0,
                    '1' => $data,
                );
                return BaseController::FailRespone($data);
                exit(0);
            }
            //还在的话就告诉前端这个用户还在登录当中
            $data = array(
                'session' => $session,
                'loginstate' => true,
            );
            //返回信息
            return BaseController::SuccessRespone($data);
        }else{
            $content = "接收的posts数据为空";
            $data = array(
                '0' => -2,
                '1' => $content,
            );
            return BaseController::FailRespone($data);   
        }
        exit(0);
    }
    /*************张嘉丽**********/
    //登出用户
    public function actionLoginout(){
        if( Yii::$app->request->isPost ){
            //接收前端请求过来的session
            $postData = Yii::$app->request->post(); //获取session
            $session = $postData['session'];
            $key = '_3rd_session:' . $session;
            //判断是否还存在这个session 
            //不存在
            $redis_value = Yii::$app->redis->get($key);
            if(empty($redis_value)){
                $content = "此用户已退出登陆";
                $data = array(
                    '0' => 0,
                    '1' => $content,
                );
                return BaseController::FailRespone($data);
                exit(0);
            }
            //存在
            //del删除session
            Yii::$app->redis->del($key);
            $data = '已成功登出';
            //返回信息
            return BaseController::SuccessRespone($data);
        }else{
            $content = "接收的posts数据为空";
            $data = array(
                '0' => -2,
                '1' => $content,
            );
            return BaseController::FailRespone($data);   
        }
        exit(0);
    }
    
    //待做
    //修改头像
    /*
    public function actionChangeurl(){
        if( Yii::$app->request->isPost ){
            $session = $postData['session'];
            $uHeadurl = 
            $key = Yii::$app->session->get($session);
            if(empty($key)){
                $content = "此用户已退出登陆";
                $data = array(
                    '0' => 0,
                    '1' => $content,
                );
                return BaseController::FailRespone($data);
                exit(0);
            }
            $uInfo = Yii::$app->redis->get($key);
            $uInfo = json_decode($uInfo, true);

            BaseController::SuccessRespone($data);
        }else{
            $content = "接收的posts数据为空";
            $data = array(
                '0' => -2,
                '1' => $content,
            );
            return BaseController::FailRespone($data);   
        }
        exit(0);
    }
    */

    /*************罗韵龙**********/
    //修改密码
    public function actionChangepass(){
        if( Yii::$app->request->isPost ){
            $postData = Yii::$app->request->post(); //获取session
            $user = new User();
            $session = $postData['session'];
            $uPassword = $postData['password'];
            $key = '_3rd_session:' . $session;
            $redis_value = Yii::$app->redis->get($key);
            if(empty($redis_value)){
                $content = "此用户已退出登陆";
                $data = array(
                    '0' => 0,
                    '1' => $content,
                );
                return BaseController::FailRespone($data);
                exit(0);
            }
            //导出uId
            $uId = BaseController::Check_session($session);
            //导出用户数据
            $uInfo = User::getPasByuId($uId);
            if($uInfo['uPassword'] == $uPassword){
                $content = '密码不能跟原密码相同';
                $data = array(
                    '0' => -3, 
                    '1' => $content,
                );
                return BaseController::FailRespone($data);
                exit(0);
            }
            $uInfo['uPassword'] = $uPassword;
            //检查密码的正确性
            $checkRules = $this->checkAll($uInfo);
            if(!empty($checkRules)){
                $content = '密码的长度在6-10位';
                $data = array(
                    '0' => -3, 
                    '1' => $content,
                );
                return BaseController::FailRespone($data);
                exit(0);
            }
            $result = $user->updatePassword($uInfo);
            if(!$result){
                $content = '密码修改失败';
                $data = array(
                    '0' => -1, 
                    '1' => $content,
                );
                return BaseController::FailRespone($data);
                exit(0);
            }
            Yii::$app->redis->del($key);
            $data = array(
                'session' => NUll,
                'loginstate' => false,
                'content' => '密码修改成功，请重新登录',
            );
            return BaseController::SuccessRespone($data);
        }else{
            $content = "接收的posts数据为空";
            $data = array(
                '0' => -2,
                '1' => $content,
            );
            return BaseController::FailRespone($data);   
        }
        exit(0);
    }
    
    /*************罗韵龙**********/
    //修改昵称
    public function actionChangename(){
        if( Yii::$app->request->isPost ){
            $postData = Yii::$app->request->post(); //获取session
            $user = new User();
            $session = $postData['session'];
            $uName = $postData['name'];
            $key = '_3rd_session:' . $session;
            $redis_value = Yii::$app->redis->get($key);
            if(empty($redis_value)){
                $content = "此用户已退出登陆";
                $data = array(
                    '0' => 0,
                    '1' => $content,
                );
                return BaseController::FailRespone($data);
                exit(0);
            }
            //导出uId
            $uId = BaseController::Check_session($session);
            //导出用户数据
            $uInfo = User::getNameByuId($uId);
            if($uInfo['uName'] == $uName){
                $content = '昵称不能跟原昵称相同';
                $data = array(
                    '0' => -3, 
                    '1' => $content,
                );
                return BaseController::FailRespone($data);
                exit(0);
            }
            $checkSame = $user->checkSameuName($uName);
            if(!empty($checkSame)){
                $content = "已经有相同的昵称，请重新输入";
                $data = array(
                    '0' => -1,
                    '1' => $content,
                );
                return BaseController::FailRespone($data);
                exit(0);
            }
            $uInfo['uName'] = $uName;
            //检查昵称的正确性
            $checkRules = $this->checkAll($uInfo);
            if(!empty($checkRules)){
                $data = array(
                    '0' => -3, 
                    '1' => $checkRules,
                );
                return BaseController::FailRespone($data);
                exit(0);
            }
            $result = $user->updateName($uInfo);
            if(!$result){
                $content = "昵称修改失败，请重新尝试n";
                $data = array(
                    '0' => -1,
                    '1' => $content,
                );
                return BaseController::FailRespone($data);
                exit(0);
            }
            $data = array(
                'session' => $session,
                'loginstate' => true,
                'content' => '昵称修改成功',
            );
            return BaseController::SuccessRespone($data);
        }else{
            $content = "接收的posts数据为空";
            $data = array(
                '0' => -2,
                '1' => $content,
            );
            return BaseController::FailRespone($data);   
        }
        exit(0);
    }



    //检查账号类型
    public function judgeAccount($account){
        $type = NUll;
        if(filter_var($account, FILTER_VALIDATE_EMAIL)){
            $type = 'mail';
        }else{
            $type = 'number';
        }
        return $type;
    }

     //检测是否有空字符
    public function checkNull($uInfo){
        //先判断是否为空
        $checkNull = array();
        $i = 0;
        foreach ($uInfo as $key => $value) {
            if(empty($value)){
                //添加数组空字符的信息
                $checkNull[$i] = $key; 
            }
            $i++;
        }
        //返回空字符的数组
        return $checkNull;
    }

    //然后判断是否符合长度
    public function checkLength($uInfo){
        $i = 0;
        $checkLength = array();
        foreach ($uInfo as $key => $value) {
            $length = strlen($value);
            if($i == 0 && $length > 16){
                $checkLength[$i] = $key;
            }else if($i == 2 && $length != 11){
                $checkLength[$i] = $key;
            }else if($i == 3 && $length >10 &&$length < 6){
                $checkLength[$i] = $key;
            }
            $i++;
        }
        return $checkLength;
    }

    //匹配字符串是否符合规则
    public function checkRules($uInfo){
        header("Content-type: text/html; charset=utf-8");
        $i = 0;
        $checkRules = array();
        foreach ($uInfo as $key => $value) {
            $rules = NUll;
            if($key == 'uName'){
                $rules = '/\/|\~|\!|\@|\#|\\$|\%|\^|\&|\*|\(|\)|\（|\）|\_|\+|\{|\}|\:|\<|\>|\?|\[|\]|\,|\.|\/|\;|\'|\`|\-|\=|\\\|\||\s+/';
                preg_match_all($rules, $value, $result);
                if(!empty($result[0])){
                    $checkRules[$i] = $key;
                }
            }else if($key == 'uNumber'){
                $rules = '/[a-z]+/';
                preg_match_all($rules, $value, $result);
                if(!empty($result[0])){
                    $checkRules[$i] = $key;
                }
            }else if($key == 'uEmail'){
                if(!filter_var($value, FILTER_VALIDATE_EMAIL)){
                    $checkRules[$i] = $key;
                }
            }
            $i++;
        }
        return $checkRules;
    }
    
    //总错误信息表
    public function checkAll($uInfo){
    	$errorContent = array();
    	$errorN = $this->checkNull($uInfo);
    	$errorL = $this->checkLength($uInfo);
    	$errorR = $this->checkRules($uInfo);
    	if(!empty($errorN)){
    		foreach ($errorN as $key => $value) {
                    $errorContent[$value] = '不能为空';
            }
    	}else if(!empty($errorL)){
    		foreach ($errorL as $key => $value) {
    			if($key == '0'){
    				$errorContent[$value] = '昵称的长度不能超过8位';
    			}else if($key == '2'){
    				$errorContent[$value] = '手机号码的长度只能11位';
    			}else if($key == '3'){
    				$errorContent[$value] = '密码的长度在6-10位';
    			}
    			
    		}
    	}else if(!empty($errorR)){
    		foreach ($errorR as $key => $value) {
    			if($value == 'uName'){
    				$errorContent[$value] = '昵称是不能含有特殊字符的中文英文数字';
    			}else if($value == 'uNumber'){
    				$errorContent[$value] = '手机号码只能全是数字';
    			}else if($value == 'uMail'){
    				$errorContent[$value] = '邮箱格式错误';
    			}
    			
    		}
    	}
    	return $errorContent;
    }

}